'''
Created on Aug 12, 2012

@author: Cihat Basol
'''


from dexen.system.client import ui, db
from dexen.system.client.controller.db_syncher import DBSyncher
from dexen.system.client.proxy import JobProxy

svr_proxy = ui.svr_proxy
db_syncher = DBSyncher()

class ArchiveSyncher(object):
    def __init__(self, job_info):
        self.job_info = job_info
        self.svr_info = job_info.get_svr_info()
        self.job_id = job_info.get_id()
    
    def synch_item(self, ind_id, archive_name):
        content = db_syncher.get_ind_archive(ind_id, archive_name, 
                                             self.job_id, self.svr_info)
        
        if content is not None or not self.svr_info.is_connected():
            return
        
        job_proxy = svr_proxy.get_job_proxy(self.job_id)
        assert isinstance(job_proxy, JobProxy)
        content = job_proxy.get_ind_archive(ind_id, archive_name)
        db_syncher.persist_ind_archive(ind_id, archive_name, content, 
                                       self.job_id, self.svr_info, False)
    
    def synch(self, ind_id):
        if not self.svr_info.is_connected():
            return
        job_proxy = svr_proxy.get_job_proxy(self.job_id)
        assert isinstance(job_proxy, JobProxy)
        archive_names = job_proxy.get_ind_archive_names(ind_id)
        for archive_name in archive_names:
            self.synch_item(ind_id, archive_name)
        db_syncher.commit()
    
